﻿using System;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Threading;

using Blackhole.Debug;

using iTunesPwned.Core.Plugin;

namespace DebugView
{
    public class DebugView : PluginBase
    {
        private DebugViewTabItem m_tabItem;

        public DebugView()
            : base(new Guid("42998CEC-4F30-4fb7-A085-65ACF195B756"), "Debug View")
        {
            this.m_tabItem = new DebugViewTabItem();

            this.m_tabItem.Tag = false;

            Garbage.Attach(new DebugViewLogger(this.m_tabItem));
        }

        public override void Init()
        {
            this.RegisterTabItem(this.m_tabItem);   
        }
    }

    public class DebugViewLogger : LoggerBase
    {
        private DebugViewTabItem m_tabItem;

        public DebugViewLogger(DebugViewTabItem tabItem)
        {
            this.m_tabItem = tabItem;
        }

        public override void Log(LoggerArguements arguements)
        {
            this.m_tabItem.LogMessage(string.Format("{0} [{1}[{2}]] {3}\n", arguements.Logged, arguements.Level, arguements.Component, arguements.Message));
        }
    }

    public class DebugViewTabItem : TabItem
    {
        private Paragraph m_paragraph;
        private RichTextBox m_debugBox;

        public DebugViewTabItem()
            : base()
        {
            this.Header = "DebugView";

            this.m_debugBox = new RichTextBox();

            this.m_debugBox.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;

            this.m_debugBox.IsReadOnly = true;

            this.m_paragraph = new Paragraph();

            FlowDocument flowDoc = new FlowDocument();

            flowDoc.Blocks.Add(this.m_paragraph);

            this.m_debugBox.Document = flowDoc;

            this.Content = this.m_debugBox;
        }

        public void LogMessage(string message)
        {
            this.m_debugBox.Dispatcher.Invoke(
                new Action<string>(this.Log),
                DispatcherPriority.Background,
                message);
        }

        private void Log(string message)
        {
            this.m_paragraph.Inlines.Add(new Run(message));

            this.m_debugBox.ScrollToEnd();
        }
    }
}
